package hackbard.piratradar;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.ClientProtocolException;

import android.app.Service;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MonitorService extends Service {

	private Timer timer = new Timer();
	public static final String PREFS_NAME = "PiratRadar";
	private LocationManager lm;
	private LocationListener locationListener;
	private Location location = null;
	private Binder mBinder = new LocalBinder();
	private Integer _UPDATE_ = 8;
	
	public class LocalBinder extends Binder {
		MonitorService getService() {
			return MonitorService.this;
		}
	}


	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		initService();
	}

	private void initService() {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		if ((settings.getLong("gpsupdate", 0) <= 300000) && settings.getInt("update", 1) < _UPDATE_){
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("update", _UPDATE_);
			editor.putLong("gpsupdate", 300000);
			Toast.makeText(getBaseContext(),
					"PiratenRadar einstellungen aktualisiert!",
					Toast.LENGTH_SHORT).show();
		}
		if (settings.getBoolean("gpsautoupdater", true)) {
			   refresh();
		       timer.scheduleAtFixedRate( new TimerTask() {
;
               public void run() {
                                                                                 
		             refresh();
                     }
                }, 0, 5*60*1000);

              }
	
			
		}


	protected void updateNotification() {
		refresh();
	}

	public void refresh() {
		Log.w("INFO", "Pirate Radar Starting refresh");
		try {
			lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locationListener = new MyLocationlistener();
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					locationListener);
			location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		} catch (Exception e) {
			Log.w("INFO", "1: " + e.getMessage());
		}
		String url = "http://piratenradar.de/output.php";
		Map<String, String> kvPairs = new HashMap<String, String>();
		kvPairs.put("lon", String.valueOf(location.getLongitude()));
		kvPairs.put("lat", String.valueOf(location.getLatitude()));
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		kvPairs.put("nick", settings.getString("nick", "anonymus"));
        /*
         * TODO: DELETE test url2 
         */
		String url2 =  "http://spitzner.org/pos.php";
		try {
			HTTPPoster.doPost(url, kvPairs);
			/*
	         * TODO: DELETE test url2 psot
	         */
			HTTPPoster.doPost(url2, kvPairs);
		} catch (ClientProtocolException e) {
			Log.w("INFO", "2: " + e.getMessage());
		} catch (IOException e) {
			Log.w("INFO", "3: " + e.getMessage());
		
		}
		Log.w("INFO", "Pirate Radar Ending refresh");
	}

	private class MyLocationlistener implements LocationListener {
		public void onLocationChanged(Location loc) {
		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
			refresh();
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}
}